package com.example.myapplication.utils;

import android.util.Log;

import com.example.myapplication.App;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.nio.charset.StandardCharsets;

import info.mqtt.android.service.Ack;
import info.mqtt.android.service.MqttAndroidClient;

public class MQTTHelper {
    private static MQTTHelper mInstance;
    private MqttAndroidClient client;
    private final String serverURI = "tcp://broker.hivemq.com:1883";
    private final String topic = "78t6e28nyf9rufdwe0im";
    private MQTTHelper() {
        client = new MqttAndroidClient(App.AppContext, serverURI,"App", Ack.AUTO_ACK);
    }
    public static MQTTHelper getInstance() {
        if(mInstance == null)
            mInstance = new MQTTHelper();
        return mInstance;
    }

    public void connect() {
        MqttConnectOptions opt = new MqttConnectOptions();
        opt.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        client.connect(opt, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.d("xxxxxxx","Connect Success");
                subscribe();
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Log.d("xxxxxxx","Connect Failure");
            }
        });
    }

    public void subscribe() {
        if(!client.isConnected()) return;
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                Log.d("xxxxxxx",message.toString());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });
        client.subscribe(topic, 1, null, new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                Log.d("xxxxxxx","Subscribe Success");
            }

            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                Log.d("xxxxxxx","Subscribe Failure");
            }
        });
    }

    public void disconnect() {
        client.disconnect();
    }
    public void unsubscribe() {
        if(!client.isConnected()) return;
        client.unsubscribe(topic);
    }

    public void publish(String data) {
        if(!client.isConnected()) return;
        client.publish(topic, new MqttMessage(data.getBytes(StandardCharsets.UTF_8)));
    }
}
